//
//  CPAUTHORController.m
//  ChinaPoem
//
//  Created by 赵俊明 on 2019/3/7.
//  Copyright © 2019 赵俊明. All rights reserved.
//

#import "CPAUTHORController.h"
#import "CPHeadFooter.h"
#import "CPAuthContentController.h"
#import "PYSearch.h"
#import "CPAuthorByAlphaVC.h"

@interface CPAUTHORController ()<UITableViewDelegate, UITableViewDataSource,PYSearchViewControllerDelegate>
@property (nonatomic, weak) UITableView *tabView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@end

@implementation CPAUTHORController
- (void)cp_rightBtn
{
    // 1.创建热门搜索
    NSMutableArray *hots = [[CPSQLTools cp_sharedInstance]  cp_search:@"author" column:@"name"];
    NSString *placholder = @"输入搜索诗人名字";
    JMSelf(ws);
    PYSearchViewController *sVC = [PYSearchViewController searchViewControllerWithHotSearches:hots searchBarPlaceholder:placholder didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        NSArray *titles = [searchText componentsSeparatedByString:@"-"];
        NSMutableArray *models = [[CPSQLTools cp_sharedInstance] cp_authorInfo:titles.firstObject];
        if (models.count > 0) {
            CPAuthContentController *iddetail = [[CPAuthContentController alloc] init];
            iddetail.model = models.firstObject;
            [searchViewController.navigationController pushViewController:iddetail animated:YES];
        }else{
            [ws cp_show:@"很抱歉，没有找到！" msg:@"没有找到" cancel:NO handle:^(BOOL isLive) {}];
        }
    }];
    
    // 3. 设置风格
    sVC.hotSearchStyle = PYHotSearchStyleDefault; // 热门搜索风格根据选择
    sVC.searchHistoryStyle = PYHotSearchStyleDefault; // 搜索历史风格为default
    sVC.delegate = self;
    CPNavController *nav = [[CPNavController alloc] initWithRootViewController:sVC];
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark - PYSearchViewControllerDelegate
- (void)searchViewController:(PYSearchViewController *)searchViewController searchTextDidChange:(UISearchBar *)seachBar searchText:(NSString *)searchText
{
    if (searchText.length) { // 与搜索条件再搜索
        NSString *sql = [NSString stringWithFormat:@"select * from author where name like ?"];
        NSString *name = [NSString stringWithFormat:@"%%%@%%", searchText];
        searchViewController.searchSuggestions = [[CPSQLTools cp_sharedInstance] cp_searchPoem:sql likeName:name column:@"name"];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.RImage = @"search";
    UITableView *sdBarTabView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kW, kH) style:(UITableViewStylePlain)];
    [sdBarTabView registerClass:[CPAuthorCell class] forCellReuseIdentifier:@"idhomeCell"];
    sdBarTabView.delegate = self;
    sdBarTabView.dataSource = self;
    sdBarTabView.backgroundColor = [UIColor clearColor];
    sdBarTabView.separatorColor = JMColorRGBA(230, 230, 230, 0.8);
    sdBarTabView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:sdBarTabView];
    self.tabView = sdBarTabView;
    [sdBarTabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(self.view);
        if (@available(iOS 11.0, *)) {
            make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.top.mas_equalTo(self.view.mas_top);
            make.bottom.mas_equalTo(self.view.mas_bottom);
        }
    }];
    [self pullRefresh];
}

- (void)pullRefresh
{
    JMSelf(weakSelf);
    self.tabView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.dataSource = [[CPSQLTools cp_sharedInstance] cp_all_authorInfo];
        sleep(.5);
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tabView reloadData];
            [weakSelf.tabView.mj_header endRefreshing];
        });
    }];
    
    [self.tabView.mj_header beginRefreshing];
}

#pragma mark --
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CPHistoryModel *model = _dataSource[section];
    return model.models.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"idhomeCell";
    CPAuthorCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {cell = [[CPAuthorCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:ID];}
    CPHistoryModel *model = _dataSource[indexPath.section];
    cell.model = model.models[indexPath.row];
    return cell;
}

// 返回索引栏
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return [self keys];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CPAuthContentController *iddetail = [[CPAuthContentController alloc] init];
    CPHistoryModel *model = self.dataSource[indexPath.section];
    iddetail.model = model.models[indexPath.row];
    [self.navigationController pushViewController:iddetail animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CPHeadFooter *headView = [CPHeadFooter cp_headTableView:tableView];
    CPHistoryModel *hM = self.dataSource[section];
    headView.groups = hM.alpha;
    headView.cp_moreAction = ^(NSString * _Nonnull group) {
        CPAuthorByAlphaVC *sec = [[CPAuthorByAlphaVC alloc] init];
        sec.alpha = group;
        [self.navigationController pushViewController:sec animated:YES];
    };
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 38;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}

- (NSArray *)keys
{
    NSMutableArray *keys = [NSMutableArray array];
    [self.dataSource enumerateObjectsUsingBlock:^(CPHistoryModel  *_Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
        [keys addObject:model.alpha];
    }];
    
    return keys.copy;
}

@end

@implementation CPAuthorCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.backgroundColor = [UIColor clearColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        UILabel *name = [[UILabel alloc] initWithFrame:CGRectZero];
        name.textAlignment = NSTextAlignmentLeft;
        name.font = kFont(20.0);
        name.textColor = [UIColor blackColor];
        [self.contentView addSubview:name];
        self.name = name;
        UILabel *content = [[UILabel alloc] initWithFrame:CGRectZero];
        content.textAlignment = NSTextAlignmentLeft;
        content.font = kFont(16.0);
        content.numberOfLines = 0;
        content.textColor = [UIColor grayColor];
        [self.contentView addSubview:content];
        self.content = content;
    }
    
    return self;
}

- (void)setModel:(CPModel *)model
{
    _model = model;
    _name.text = model.cp_author;
    _content.text = model.cp_content;
    self.alpha = 0.0;
    JMSelf(ws);
    [UIView animateWithDuration:0.4 animations:^{ws.alpha = 1.0;}];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat mar = 10;
    _name.frame = CGRectMake(10, mar, self.width*0.7,25);
    _content.frame = CGRectMake(10, CGRectGetMaxY(_name.frame), self.width-20, self.height-35);
}

@end
